/**
* 角色照片及角色图像资源相关
* */
import axios from 'axios'
import fs from 'node:fs'
import lodash from 'lodash'
import path from 'path'
import { Cfg } from '#miao'

// 定义资源路径
const rPath = `${process.cwd()}/plugins/miao-plugin/resources`

const CharImg = {
  async getCardImg(names) {
    let list = []
    let addImg = async function (charImgPath, disable = false) {
      let dirPath = `./plugins/miao-plugin/resources/${charImgPath}`

      // 如果路径不存在，则创建
      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath)
      }
      // 如果禁用，则返回
      if (disable) {
        return
      }

      // 从API获取图片
      for (let i = 0; i < names.length; i++) {
        let url = `http://api.zvmiy.top/${names[i]}`
        let response = await axios({
          url,
          method: 'GET',
          responseType: 'stream'
        })

        const writer = fs.createWriteStream(path.join(dirPath, `${names[i]}.jpg`))

        response.data.pipe(writer)

        let error = false
        await new Promise((resolve, reject) => {
          writer.on('finish', resolve)
          writer.on('error', (err) => {
            error = true
            reject(err)
          })
        })

        if (error) {
          // 如果出错，尝试获取上一张图片
          if (i > 0) {
            i--
          }
        } else {
          // 如果成功，将图片路径添加到列表中
          list.push(path.join(dirPath, `${names[i]}.jpg`))
          // 每30张图片一循环
          if (list.length % 30 === 0) {
            // do something
          }
        }
      }
    }
    await addImg('charImgPath')
    return list
  },

  getRandomImg(imgPath, defImg = []) {
    // 遍历图像路径，寻找可用的图像
    let allImgPath = imgPath.concat(defImg)
    for (let img of allImgPath) {
      let ret = []
      for (let type of ['webp', 'png']) {
        if (fs.existsSync(`${rPath}/${img}.${type}`)) {
          ret.push(img + `.${type}`)
        }
      }
      if (fs.existsSync(`${rPath}/${img}`)) {
        let imgs = fs.readdirSync(`${rPath}/${img}`).filter((file) => {
          return /\.(png|webp)$/.test(file)
        })
        for (let img of imgs) {
          ret.push(`${img}/${encodeURIComponent(img)}`)
        }
      }
      // 如果找到图像，则返回
      if (ret.length > 0) {
        return lodash.sample(ret)
      }
    }

    // 如果没有找到图像，则返回默认图像
    for (let defImg of defImg) {
      if (fs.existsSync(`${rPath}/${defImg}`)) {
        return defImg
      }
    }
  },

  getImgs(costumeIdx = '', travelerElem = '', weaponType = 'sword', talentCons) {
    let fileType = 'webp'
    costumeIdx = costumeIdx === '2' ? '2' : ''
    let imgs = {}
    if (!['空', '荧', '旅行者'].includes(Cfg.name)) {
      travelerElem = ''
    }
    const nPath = `/meta-gs/character/`
    const tPath = `/meta-gs/character/旅行者/${travelerElem}/`
    let add = (key, path) => {
      imgs[key] = `${nPath}${path}.${fileType}`
    }
    let tAdd = (key, path) => {
      imgs[key] = `${travelerElem ? tPath : nPath}${path}.${fileType}`
    }
    add('face', 'imgs/face')
    add('qFace', 'imgs/face-q')
    add('side', 'imgs/side')
    add('gacha', 'imgs/gacha')
    add('splash', 'imgs/splash')
    tAdd('card', 'imgs/card')
    tAdd('banner', 'imgs/banner')
    for (let i = 1; i <= 6; i++) {
      tAdd(`cons${i}`, `icons/cons-${i}`)
    }
    for (let i = 0; i <= 3; i++) {
      tAdd(`passive${i}`, `icons/passive-${i}`)
    }
    imgs.a = `/common/item/atk-${weaponType}.webp`
    for (let t of ['e', 'q']) {
      imgs[t] = talentCons[t] > 0 ? imgs[`cons${talentCons[t]}`] : `${nPath}icons/talent-${t}.webp`
    }
    return imgs
  },

  getImgsSr(talentCons) {
    let fileType = 'webp'
    const nPath = `/meta-sr/character/`
    let imgs = {}
    let add = (key, path) => {
      imgs[key] = `${nPath}${path}.${fileType}`
    }
    add('face', 'imgs/face')
    add('splash', 'imgs/splash')
    add('preview', 'imgs/preview')
    for (let i = 1; i <= 3; i++) {
      add(`tree${i}`, `imgs/tree-${i}`)
    }
    for (let key of ['a', 'e', 'q', 't', 'z', 'a2', 'e2']) {
      add(key, `imgs/talent-${key}`)
    }
    for (let i = 1; i <= 6; i++) {
      if (i !== 3 && i !== 5) {
        add(`cons${i}`, `imgs/cons-${i}`)
      }
    }
    imgs.banner = 'meta-sr/character/common/imgs/banner.webp'
    imgs.card = 'meta-sr/character/common/imgs/card.webp'
    imgs.cons3 = imgs[talentCons[3]]
    imgs.cons5 = imgs[talentCons[5]]
    return imgs
  }
}
export default CharImg
